﻿using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    internal struct DXFN12
    {
        private DXFN _Dxfn;
        private bool _hasDXFn;
        internal XFExtNoFRT xfext;
        private bool _hasxfext;

        public void Read(BinaryReader reader)
        {
#if DEBUG
            ReadWriteChecker.CheckStruct((ref DXFN12 t, BinaryReader r) => t.Read(r),
                                         (ref DXFN12 t, BinaryWriter w) => t.Write(w), reader, ref this);
            var pos0 = reader.BaseStream.Position;
#endif
            var cbDxf = reader.ReadUInt32();
            if (cbDxf == 0)
            {
                reader.ReadUInt16();
                return;
            }
            var pos = reader.BaseStream.Position;
            _hasDXFn = true;
            _Dxfn.Read(reader);
            if (cbDxf == reader.BaseStream.Position - pos)
                return;
            _hasxfext = true;
#if DEBUG
            Contract.Assert(reader.BaseStream.Position > pos0);
#endif
            xfext.Read(reader);
        }

        public void Write(BinaryWriter writer)
        {
            uint size = 0;
            var position = writer.BaseStream.Position;
            writer.Write(size);

            if (_hasDXFn)
                _Dxfn.Write(writer);
            
            if (_hasxfext)
                xfext.Write(writer);
            if (!_hasDXFn && !_hasxfext)
            {
                writer.Write((ushort) 0);
                return;
            }
            var newPosition = writer.BaseStream.Position;
            size = (uint) (newPosition - position - 4);
            writer.BaseStream.Position = position;
            writer.Write(size);
            writer.BaseStream.Position = newPosition;

        }

        public void SetFromDifferencialStyleRecord(DifferentialStyleRecord record, BiffWriterWorkbookContext context)
        {
            _hasDXFn = true;
            _Dxfn.SetFromDifferencialStyleRecord(record, context);
            this.xfext = new XFExtNoFRT();
        }

        public void AddProperty(ExtProp create)
        {
            this.xfext.AddProperty(create);
            this._hasxfext = true;
        }
    }
}